import axios from 'axios'

const request = axios.create({
  baseURL: process.env.VUE_APP_SERVER_URL,
  timeout: 5000
})

request.interceptors.request.use(
  config => {
    const newConfig = { ...config }
    const TOKEN = localStorage.getItem('token')
    if (TOKEN) {
      newConfig.headers.Authorization = `Bearer ${TOKEN}`
    }
    return newConfig
  },
  error => Promise.reject(error)
)

request.interceptors.response.use(
  res => {
    return res.data
  },
  error => {
    const { response } = error
    const status = response.status
    if (status === 401) {
      localStorage.clear()
    } else {
      alert(error.response.data.message)
      return Promise.reject(error)
    }
  }
)

export default {
  post (url = '', data = {}, config = {}) {
    return request.post(url, data, config)
  },
  put (url = '', data = {}, config = {}) {
    return request.put(url, data, config)
  },
  patch (url = '', data = {}, config = {}) {
    return request.patch(url, data, config)
  },
  get (url = '', params = {}, config = {}) {
    const OPTIONS = Object.assign({ params }, config)
    return request.get(url, OPTIONS)
  },
  delete (url = '', params = {}, config = {}) {
    const OPTIONS = Object.assign({ params }, config)
    return request.delete(url, OPTIONS)
  }
}
